package ar.uade.edu.fain.ad.client.web.servlet.empleado;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ar.uade.edu.fain.ad.client.delegate.EmpleadoServiceDelegate;
import ar.uade.edu.fain.ad.client.web.servlet.BaseServlet;
import ar.uade.edu.fain.ad.common.exception.AccesoDenegadoException;
import ar.uade.edu.fain.ad.common.transfer.LoginVO;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	private EmpleadoServiceDelegate empleadoServiceDelegate;

	/**
	 * @see BaseServlet#BaseServlet()
	 */
	public LoginServlet() {
		super();
	}

	@Override
	public void init() throws ServletException {
		super.init();
		this.empleadoServiceDelegate = getDelegateFactory()
				.createEmpleadoDelegate();
	}

	public EmpleadoServiceDelegate getEmpleadoServiceDelegate() {
		return empleadoServiceDelegate;
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		forward(getViewBasePath() + "login.jsp", request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		final String username = request.getParameter("username");
		final String password = request.getParameter("password");
		try {
			final LoginVO loginVO = 
					getEmpleadoServiceDelegate().login(username, password);
			final HttpSession session = request.getSession();
			session.setAttribute("loginVO", loginVO);
			session.setAttribute("mozoId", loginVO.getEmpleadoVO().getId());
			session.setAttribute("localId", loginVO.getLocalId());
			session.setAttribute("cajaId", loginVO.getAreaId());
			session.setAttribute("salonId", loginVO.getAreaId());
			session.setAttribute("rolEmpleado", 
					loginVO.getRol().name().toUpperCase());
			response.sendRedirect(request.getContextPath() + "/index.html");
		} catch (AccesoDenegadoException e) {
			forward(getViewBasePath() + "denegado.jsp", request, response);
		}
	}

	@Override
	protected String getViewBasePath() {
		return "/pages/empleado/";
	}

}
